<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion">后台管理</i>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加管理员</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-input v-model="ruleForm.avatar"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="enable">
        <el-switch v-model="ruleForm.enable" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ccc"></el-switch>
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select multiple v-model="ruleForm.roleIds" placeholder="请选择">
          <el-option v-for="item in roleListOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"> 添加 </el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用

  name: "AdminAddNew",
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      roleListOptions: [],
      ruleForm: {
        username: "chen",
        password: "123456",
        nickname: "chen",
        avatar: "www.baidu.com",
        phone: "15079366080",
        email: "824293878@qq.com",
        description: "暂无",
        enable: 1,
        roleIds: [],
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 4,
            max: 15,
            message: "长度在 4 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        avatar: [
          { required: true, message: "请输入头像URL", trigger: "blur" },
          {
            min: 4,
            max: 255,
            message: "长度在 4 到 255 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入简介", trigger: "blur" },
          {
            min: 2,
            max: 255,
            message: "长度在 2 到 255 个字符",
            trigger: "blur",
          },
        ],
        roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    loadRoleList() {
      let url = "http://localhost:9088/roles";
      console.log("url = " + url);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .get(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.roleListOptions = responseBody.data;
            this.ruleForm.roleIds = this.roleListOptions.id;
          } else {
            this.$message.error(responseBody.message);
          }
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          let url = "http://localhost:9088/admins/add-new";
          console.log("url = " + url);
          let formData = this.qs.stringify(this.ruleForm);
          console.log("formData = " + formData);
          this.axios
            .create({
              headers: {
                Authorization: localStorage.getItem("jwt"),
              },
            })
            .post(url, formData)
            .then((response) => {
              let responseBody = response.data;
              if (responseBody.state == 20000) {
                this.$message({
                  showClose: true,
                  message: "添加管理员成功！",
                  type: "success",
                });
                this.resetForm(formName);
              } else {
                this.$message.error(responseBody.message);
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {},
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.loadRoleList();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
